package org.star.dolphin.service;

import com.alibaba.fastjson.JSON;
import org.star.dolphin.annotation.AccessLimit;
import org.star.dolphin.annotation.OpenApi;
import org.star.dolphin.factory.ResponseMessageFactory;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface IRequestService {

    /**
     * 接口授权
     *
     * @param request
     * @param response
     * @return
     */
    Boolean authorize(HttpServletRequest request, HttpServletResponse response);

    /**
     * 请求结束
     */
    void endRequest();

    /**
     * 授权失败
     * 设置响应为401
     *
     * @param response
     * @return
     */
    default Boolean authorizeFail(HttpServletResponse response) {
        try {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSON.toJSONString(ResponseMessageFactory.error("未获授权", null, 401)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 路由错误
     * 设置响应为404
     *
     * @param response
     * @return
     */
    default Boolean routeFail(HttpServletResponse response) {
        try {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * preHandle
     *
     * @param request
     * @param response
     * @param handler
     * @return
     */
    default Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;

            //获取请求限制注解
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            //判断是否是限制接口
            if (!ObjectUtils.isEmpty(accessLimit)) {
                if (!accessLimitProcess(request, accessLimit)) {
                    return false;
                }
            }

            //获取方法权限注解
            OpenApi openApi = handlerMethod.getMethodAnnotation(OpenApi.class);
            //判断是否是开放接口
            if (!ObjectUtils.isEmpty(openApi)) {
                return true;
            } else {
                //授权检查
                return authorize(request, response);
            }
        } else {
            return routeFail(response);
        }
    }

    /**
     * @param accessLimit
     * @return
     */
    default Boolean accessLimitProcess(HttpServletRequest request, AccessLimit accessLimit) {
        return true;
    }
}
